package com.example.cardgame

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.ImageView
import androidx.gridlayout.widget.GridLayout
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.ui.graphics.Color
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.children
import cn.edu.sicnu.cardgame.CardMatchingGame

class MainActivity : AppCompatActivity(),View.OnClickListener {
    lateinit var game:CardMatchingGame
    val cardButtons = mutableListOf<Button>()
    private lateinit var score: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        score = findViewById(R.id.score)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        val gridLayout = findViewById<GridLayout>(R.id.gridlayout)
        for(v in gridLayout.children){
            if(v is Button){
                v.setOnClickListener(this)
                cardButtons.add(v)
            }
        }
        game = CardMatchingGame(cardButtons.count())
        updateUI()

        val reset = findViewById<Button>(R.id.reset)
        reset.setOnClickListener{
            game = CardMatchingGame(cardButtons.count())
            updateUI()
        }
    }

    fun updateUI(){
        for(button in cardButtons){
            val index = cardButtons.indexOf(button)
            val card = game.cardAtIndex(index)
            button.isEnabled != card.isMatched
            if(card.isChosen){
                button.text = card.toString()
                button.setBackgroundColor(android.graphics.Color.WHITE)
            }else{
                button.text = ""
                button.setBackgroundResource(R.drawable.card)
            }
        }
        val score = findViewById<TextView>(R.id.score)
        score.text = String.format("%s%d","Score:",game.score)
    }

    override fun onClick(v : View?){
        if(v is Button){
            val index = cardButtons.indexOf(v)
            game.chooseCardAtIndex(index)
            updateUI()
        }
    }

    fun onSave(view: View) {
        val currentScore = game.score // 获取当前得分
        // 创建 Intent，并传递信息
        val intent = Intent(this, InfoActivity::class.java).apply {
            putExtra("score", currentScore) // 传递当前得分
        }
        // 启动 InfoActivity
        startActivity(intent)
        finish()
        }

}